<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <input type="text" v-model="searchName">
        <ul>
            <li v-for="(p, index) in filterPersons" :key="p.id">
                {{p.id}}---{{p.name}}---{{p.age}}
            </li>
        </ul>
        <button @click="sortType=2">按年龄升序</button>
        <button @click="sortType=3">按年龄降序</button>
        <button @click="sortType=1">原本顺序</button>
    </div>


  <script type="text/javascript" src="../js/vue.js"></script>
  <script type="text/javascript">
        new Vue({
            el:'#app',
            data(){
                return{
                    searchName:'',
                    sortType:[1,2,3],//1:不排序 2：升序 3:降序
                    persons:[
                    {id:1,name:'Tom',age:15},
                    {id:2,name:'Jack',age:12},
                    {id:3,name:'Bob',age:16},
                    {id:4,name:'Mike',age:13},
                    {id:5,name:'John',age:18},
                ]
             }
            },
            computed: {
                //过滤后的新数组
                filterPersons(){
                    //1.取出依赖数据
                     const{searchName,persons,sortType}=this
                    //2.计算产生一个新数据
                    //数组过滤
                     const arr=persons.filter((p,index)=>p.name.indexOf(searchName)!==-1)
                     //有可能要排序(升/降)
                     if(sortType!==1){
                        arr.sort((p1,p2)=>{//如果返回值大于0，将p2放在左边。
                            if(sortType===3){//降序
                                return p2.age-p1.age
                            }else{//升序
                                 return p1.age-p2.age
                            }
                           
                        })
                     }
                    //3.返回新数据
                    return arr
                }
            },
        })
  </script>
</body>
</html>